package com.xunshibao.tutor.user.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xunshibao.core.dao.DaoUtils;
import com.xunshibao.core.page.Pagination;
import com.xunshibao.tutor.common.AreaServiceImpl;
import com.xunshibao.tutor.po.TutorInfo;
import com.xunshibao.tutor.po.TutorInfo.STATUS;
import com.xunshibao.tutor.po.ext.TutorInfoExt;
import com.xunshibao.tutor.user.dao.TutorInfoDaoImpl;

@Service
public class TutorInfoServiceImpl {
    @Autowired
    private TutorInfoDaoImpl infoDao;
    @Autowired
    private AreaServiceImpl areaService;
    
    public int save(TutorInfo info,  String ip, Long userid) {
        Date now = new Date();
        info.setIp(ip);
        info.setTid(userid);
        info.setLudt(now);
        info.setPdt(now);
        info.setTimes(0);
        info.setStatus(TutorInfo.STATUS.VALID.value());
        return infoDao.save(info);
    }

    public int update(Long infoId, TutorInfo info, String ip, Long userid) {
        TutorInfo dbInfo = infoDao.userInfo(infoId, userid);
        if(dbInfo != null) {
            info.setIp(ip);
            info.setLudt(new Date());
            List<String> columns = new LinkedList<String>();
            List<Object> values = new LinkedList<Object>();
            List<String> excludeProps = new ArrayList<String>();
            excludeProps.add("pdt");
            excludeProps.add("tid");
            excludeProps.add("id");
            excludeProps.add("times");
            excludeProps.add("status");
            DaoUtils.getUpdateFields(dbInfo, info, columns, values, excludeProps, true);
            if(!columns.isEmpty()) {
                values.add(infoId);
                return infoDao.update(columns.toArray(new String[columns.size()]), values.toArray(new Object[values.size()]), "id=?");
            }
            return 1;//没有更新，这个只和更新成功的值是相同的。
        } else {
            return -3;//要更新的记录不存在
        }
    }
    
    public Pagination list(Integer pageNo, Integer pageSize) {
    	Pagination page = infoDao.list(STATUS.VALID, pageNo, pageSize);
    	@SuppressWarnings("unchecked")
		List<TutorInfoExt> infos = (List<TutorInfoExt>) page.getList();
    	if(infos != null) {
    		String area = null;
    		for(TutorInfoExt info : infos) {
    			area = areaService.pareArea(info.getArea());
    			info.setAreaName(area);
    		}
    	}
        return page;
    }
    
    public TutorInfo view(Long infoId) {
    	TutorInfo info = infoDao.getById(infoId);
    	if(info != null) {
    		info.setArea(areaService.pareArea(info.getArea()));
    		infoDao.update(new String[]{"times"}, new Object[]{info.getTimes()+1, info.getId()}, "id=?");
    	}
    	
    	return info;
    }
}
